//
//  HTStatusViewModel.swift
//  mySinaBlog
//
//  Created by whtapple on 3/27/16.
//  Copyright © 2016 whtapple. All rights reserved.
//

import UIKit

class HTStatusViewModel: NSObject {
    //判断是否在加载数据属性
    private var isloading: Bool = false
    //单例
    static let sharedInstance: HTStatusViewModel = HTStatusViewModel()
    private override init() {
        super.init()
    }
    //加载状态数据
    func loadStatusData(since_id: Int64,max_id: Int64,loadstutas: (model: [HTStatus]?,error: NSError?) -> ()){
        //判断是否在加载数据
        if self.isloading == true{
            return
        }
        //到这里说明没有在加载数据，将状态改为在加载数据
        self.isloading = true
        //URL
        let urlstring = "https://api.weibo.com/2/statuses/home_timeline.json"
        //参数
        var parameters: [String : AnyObject] = ["access_token" : HTUserAccountViewModel.sharedInstance.userAccount!.access_token!]
        //添加两个约束用户上拉刷新和下拉刷新
        if since_id > 0 {
            parameters["since_id"] = NSNumber(longLong: since_id)
        }else if max_id > 0{
            parameters["max_id"] = NSNumber(longLong: max_id - 1)
        }
        //加载网络
        let network = HTNetworkTool.sharedInstanse
        network.requestGET(urlstring, parameters: parameters) { (result, error) -> () in
            //数据加载完成，改为没有加载数据
            self.isloading = false
            //为空时调用为空的方法，返回
            if error != nil {
                loadstutas(model: nil, error: error)
                return
            }
             //拿到数组
            let arr = result?["statuses"] as? [[String : AnyObject]]
            //创建一个数组装数据
            var arrM = [HTStatus]()
            //遍历数组，拿到数组转化为模型
            for dict in arr! {
                let status = HTStatus(dict: dict)
                arrM.append(status)
            }
            //调用方法
            loadstutas(model: arrM, error: nil)
        }
    }
}
